package cn.cjx.pet.service.impl;

import cn.cjx.basic.exception.BusinessException;
import cn.cjx.basic.service.impl.BaseServiceImpl;
import cn.cjx.basic.utils.BaiduAuditUtils;
import cn.cjx.basic.utils.QueryResult;

import cn.cjx.pet.domain.Pet;
import cn.cjx.pet.domain.PetDetail;
import cn.cjx.pet.domain.PetOnlineAuditLog;
import cn.cjx.pet.domain.PetType;
import cn.cjx.pet.mapper.PetDetailMapper;
import cn.cjx.pet.mapper.PetMapper;
import cn.cjx.pet.mapper.PetOnlineAuditLogMapper;
import cn.cjx.pet.mapper.PetTypeMapper;
import cn.cjx.pet.query.PetTypeQuery;
import cn.cjx.pet.service.IPetService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author cjx
 * @since 2022-05-17
 */
@Service
public class PetServiceImpl extends BaseServiceImpl<Pet> implements IPetService {

	@Autowired
	private PetMapper petMapper;

	@Autowired
	private PetTypeMapper petTypeMapper;

	@Autowired
	private PetDetailMapper petDetailMapper;

	@Autowired
	private PetOnlineAuditLogMapper petOnlineAuditLogMapper;

	/*
	 * 关联查询
	 * */
	@Override
	public QueryResult<PetType> queryPetTypes(PetTypeQuery query) {
		List<PetType> shops = petTypeMapper.queryPetTypes(query);
		//shops.forEach(System.out::println);
		// skip(5) 前面5个排除了
		List<PetType> collect = shops.stream().skip(query.getPageSize()* (query.getCurrentPage()-1) ).limit(query.getPageSize()).collect(Collectors.toList());
		Long aLong = Long.valueOf(shops.size());
		return new QueryResult<PetType>(aLong,collect);
	}

	@Override
	public void save(Pet pet) {
		petMapper.save(pet);
		PetDetail petDetail = pet.getPetDetail();

		if (petDetail == null) {
			throw new BusinessException("请填写您的宠物描述和介绍");
		}
		petDetail.setPetId(pet.getId());
		petDetailMapper.save(petDetail);
	}


	@Override
	public void offSale(List<Long> ids) {
		Map<String, Object> map = new HashMap<>();
		map.put("ids",ids);
		map.put("offSaleTime",new Date());
		petMapper.offSale(map);

	}

	@Override
	public void onSale(List<Long> ids) {

		for (Long id : ids) {
			//审核
			Pet pet = petMapper.loadById(id);
			StringBuffer stringBuffer = new StringBuffer();
			if (!BaiduAuditUtils.TextCensor(pet.getName())) {
				stringBuffer.append(pet.getName() + "不符合要求");
			}

			/*if(BaiduAuditUtils.ImgCensor( " http://dfs.java.itsource.cn" + pet.getResources().split(","))) {
				stringBuffer.append("该图片不合法");
			}*/

			if (stringBuffer.length() > 0){
				PetOnlineAuditLog auditLog = new PetOnlineAuditLog();
				auditLog.setPetId(id);
				auditLog.setNote(stringBuffer.toString());
				petOnlineAuditLogMapper.save(auditLog);
				System.out.println("您的审核未通过，请查询原因修改后重新申请");
				//TODO 使用短信或邮箱验证码
				continue;
			}
			pet.setState(1);
			pet.setOnsaletime(new Date());
			petMapper.update(pet);
		}


	}
}


